package com.example.shopspring.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.shopspring.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info("token:{}", token);
        try {
            //如果验证成功放行请求
            DecodedJWT verify = JWTUtil.verify(token);
            return true;
        } catch (Exception exception) {
            response.setContentType("application/json;charset=UTF-8");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 203);
            jsonObject.put("msg", "请先登录");
            PrintWriter out = response.getWriter();
            out.append(jsonObject.toString());
            return false;
        }
    }
}
